package com.atguigu.day02;

/**
 * @auther zzyy
 * @create 2020-03-26 12:32
 * 多线程之间按顺序调用，实现线程1->线程2->线程3
 * 三个线程启动，要求如下：
 *
 * 线程1打印5次，线程2打印10次，线程3打印15次
 * 接着
 * 线程1打印5次，线程2打印10次，线程3打印15次
 * ......三个线程来10轮
 *
 * 精确通知，按照顺序走
 *
 * 1 线程 操作 资源类
 * 2 判断、干活、通知
 * 3 while
 * 4 线程标志位的修改，update操作
 */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class M1{
    private int num=1;
    Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();


    public void print5() throws InterruptedException {
        lock.lock();
        try{
        while (num!=1){
            condition1.await();
        }
            for (int i = 1; i <6 ; i++) {
                System.out.println(Thread.currentThread().getName()+"打印第"+i+"次");
            }
            num=2;
            condition2.signal();
        }finally {
            lock.unlock();
        }
    }

    public void print10() throws InterruptedException {
        lock.lock();
        try{
            while (num!=2){
                condition2.await();
            }
            for (int i = 1; i <11 ; i++) {
                System.out.println(Thread.currentThread().getName()+"打印第"+i+"次");
            }
            num=3;
            condition3.signal();
        }finally {
            lock.unlock();
        }
    }

    public void print15() throws InterruptedException {
        lock.lock();
        try{
            while (num!=3){
                condition3.await();
            }
            for (int i = 1; i <16 ; i++) {
                System.out.println(Thread.currentThread().getName()+"打印第"+i+"次");
            }
            num=1;
            condition1.signal();
        }finally {
            lock.unlock();
        }
    }


}





public class ThreadAndAccess {

    public static void main(String[] args) {
        M1 m1 = new M1();


            new Thread(() -> {
                for (int i = 0; i <1 ; i--) {
                    try {
                        m1.print5();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            },"线程1").start();

        new Thread(() -> {
            for (int i = 0; i <1 ; i--) {
                try {
                    m1.print10();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程2").start();


        new Thread(() -> {
            for (int i = 0; i <1 ; i--) {
                try {
                    m1.print15();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"线程3").start();





    }
}
